package com.yenlien.traceyun.usercenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.crypt.CryptUtil;
import com.yenlien.traceyun.usercenter.controller.form.GovConfigForm;
import com.yenlien.traceyun.usercenter.dao.*;
import com.yenlien.traceyun.usercenter.entity.Company;
import com.yenlien.traceyun.usercenter.entity.CompanyCustomAppVersion;
import com.yenlien.traceyun.usercenter.entity.CompanyExamined;
import com.yenlien.traceyun.usercenter.entity.User;
import com.yenlien.traceyun.usercenter.service.CompanyExaminedService;
import com.yenlien.traceyun.usercenter.service.CompanyService;
import com.yenlien.traceyun.usercenter.service.GovConfigService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping(value = "/company")
public class CompanyController extends BaseController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private GovConfigService govConfigService;

    @Autowired
    private CompanyExaminedService companyExaminedService;

    @Autowired
    private CustomAppVersionDao customAppVersionDao;

    @Autowired
    private CompanyCustomAppVersionDao companyCustomAppVersionDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private GovConfigDao govConfigDao;

    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody Company company) {
        return buildPage(companyService.findByList(company));
    }

    @RequestMapping(value = "/findFruitCompList", method = RequestMethod.POST)
    public Object findFruitCompList(@RequestBody Company company) {
        return success(companyService.findFruitCompList(company));
    }
    @RequestMapping(value = "/findAllFruitCompList", method = RequestMethod.GET)
    public Object findAllFruitCompList() {
        return success(companyService.findAllFruitCompList());
    }

    @RequestMapping(value = "/getUserNum")
    public Object getUserNum(@RequestBody Company company) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(company.getParentId())) {
            return userDao.getAllUser(company.getParentId()).stream().map(User::getCompanyId).collect(Collectors.toList());
        } else {
            return userDao.getAllUser(company.getId()).stream().map(User::getCompanyId).collect(Collectors.toList());
        }
    }

    @RequestMapping(value = "/companyNumber")
    public Object companyNumber(@RequestBody Company company) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(company.getParentId())) {
            return companyDao.companyNumber(company.getParentId()).stream().map(Company::getId).collect(Collectors.toList());
        } else {
            return companyDao.companyNumber(company.getId()).stream().map(Company::getId).collect(Collectors.toList());
        }
    }

    @RequestMapping(value = "/companyActivation")
    public Object companyActivation(@RequestBody Company company) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(company.getParentId())) {
            return companyDao.companyNumber(company.getParentId()).size();
        } else {
            return companyDao.companyNumber(company.getId()).size();
        }
    }

    /**
     * 根据type加载所有
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/findByType/{type}", method = RequestMethod.GET)
    public Object findAllGov(@PathVariable String type) {
        return success(companyDao.findByType(type));
    }

    /**
     * 审核
     *
     * @param examined
     * @return
     */
    @PostMapping(value = "/examined")
    public Object examined(@RequestBody CompanyExamined examined) {
        companyExaminedService.examined(examined);
        return success("ok");
    }

    @GetMapping(value = "/examinedlist/{companyId}")
    public Object examinedList(@PathVariable("companyId") String companyId) {
        return success(companyExaminedService.list(companyId));
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable String id) {
        return success(companyService.findById(id));
    }

    @RequestMapping(value = "/findParentById/{id}", method = RequestMethod.GET)
    public Object findParentById(@PathVariable String id) {
        return success(companyService.findParentById(id));
    }

    @GetMapping(value = "/findTypeById/{id}")
    public Object findTypeId(@PathVariable String id) {
        return success(companyService.findTypeById(id));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(Company company, HttpServletRequest request) throws Exception {
        CheckParams.checkBean(company, new String[]{"name"});
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        Company p = companyService.save(company, files);
        return success(p);
    }

    @RequestMapping(value = "/save2", method = RequestMethod.POST)
    public Object save2(@RequestBody Company company) throws Exception {
        CheckParams.checkBean(company, new String[]{"name"});
        Company p = companyService.save2(company);
        return success(p);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(Company company, HttpServletRequest request) throws Exception {
        CheckParams.checkBean(company, new String[]{"name"});
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        Company p = companyService.update(company, files);
        return success(p);
    }



    @RequestMapping(value = "/update2", method = RequestMethod.POST)
    public Object update2(@RequestBody Company company) throws Exception {
        CheckParams.checkBean(company, new String[]{"name"});
        Company p = companyService.update2(company);
        return success(p);
    }




    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    public Object update(@RequestBody Company company) {
        return success(companyService.updateInfo(company));
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Object delete(@PathVariable String id) {
        companyService.delete(id);
        return success("success");
    }

    /**
     * 查询公司数量
     *
     * @return
     */
    @PostMapping(value = "/number")
    public Object number() {
        return success(companyService.number());
    }

    /**
     * 设置企业管理app
     *
     * @return
     */
    @RequestMapping(value = "/gov/setcustomapp", method = RequestMethod.POST)
    public Object setCustomAppVersion(GovConfigForm form, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        govConfigService.setGovConfig(form, files);
        return success("ok");
    }

    /**
     * 设置企业管理app
     *
     * @return
     */
    @RequestMapping(value = "/company/setcustomapp", method = RequestMethod.POST)
    public Object setCustomAppVersion(@RequestBody JSONArray array) throws Exception {

        if (array != null && array.size() > 0) {
            List<CompanyCustomAppVersion> companyCustomAppVersions = array.toJavaList(CompanyCustomAppVersion.class);
            companyCustomAppVersionDao.saveAll(companyCustomAppVersions);
        }

        return success("ok");
    }

    /**
     * 获取企业已绑定的以应用
     *
     * @param companyId
     * @return
     */
    @GetMapping(value = "/get/customapp/{companyId}")
    public Object getCustomApp(@PathVariable String companyId) {
        return success(companyCustomAppVersionDao.findByCompanyId(companyId));
    }

    /**
     * 获取政府配置
     *
     * @return
     */
    @GetMapping(value = "/get/govconfig/{companyId}")
    public Object getGovConfig(@PathVariable String companyId) {
        return success(govConfigDao.findByCompanyId(companyId));
    }

    /**
     * 修改授权时间
     *
     * @return
     */
    @PostMapping(value = "/change/expiretime")
    public Object chenageExpiretime(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"companyId", "expiretimeEnd", "expiretime"});
        Company company = companyDao.findById(params.getString("companyId"));
        company.setExpiretimeEnd(params.getString("expiretimeEnd"));
        company.setExpiretime(params.getString("expiretime"));
        companyDao.save(company);
        return success("ok");
    }

    /**
     * 重置密码
     */
    @PostMapping(value = "/resetpassword")
    public Object resetPassword(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"companyId", "password"});
        Company company = companyDao.findById(param.getString("companyId"));
        User user = userDao.findById(company.getUserId());
        user.setPassword(CryptUtil.md5(param.getString("password")));
        userDao.save(user);
        return success("ok");
    }

    /**
     * 查询新增企业
     *
     * @return
     */
    @PostMapping("/newCompanys")
    public Object newCompanys() {
        return success(companyService.newCompanys());
    }

    /**
     * 查询累计的用户
     *
     * @return
     */
    @PostMapping("/cumCompanys")
    public Object cumCompanys() {
        return success(companyService.cumCompanys());
    }


    /**
     * 查询数据中心企业数量
     *
     * @return
     */
    @PostMapping("/firm")
    public Object firm(@RequestBody JSONObject param) {
        String companyId = param.getString("companyId");
        return success(companyService.firm(companyId));
    }

    /**
     * 查询已审核公司
     *
     * @return
     */
    @PostMapping("/audit")
    public Object audit() {
        String audit = "1";
        return success(companyService.audit(audit));
    }


    /**
     * 获取政府配置
     *
     * @return
     */
    @GetMapping(value = "/get/child/{companyId}")
    public Object getchild(@PathVariable("companyId") String companyId) {
        return success(companyDao.findByParentId(companyId));
    }


    @GetMapping(value = "get/plantCompany/{companyId}")
    public Object getCompanyId(@PathVariable("companyId") String companyId) {
        return success(companyDao.findById(companyId));
    }

    /**
     * 查询指定应用下的企业
     *
     * @param customAppId
     * @return
     */
    @GetMapping(value = "/getCompanyByCustomAppId")
    public Object getCompanyByCustomAppId(String customAppId) {
        return success(companyDao.getCompanyByCustomAppId(customAppId));
    }


    /**
     * 根据企业id查询数据中心配置的扫码量，符码量信息
     */
    @GetMapping(value = "/findByCompanyIdMaxScan/{companyId}")
    public Object findByCompanyIdMaxScan(@PathVariable("companyId") String companyId) {
        Map<String, Object> map = companyCustomAppVersionDao.findByCompanyIdMaxScan(companyId);
        JSONObject obj = new JSONObject();
        obj.put("map", map);
        return obj;
    }

    /**
     * 更新最大扫码数跟最大符码数
     */
    @PostMapping(value = "/updateMaxPrintAndMaxScan")
    public Object updateMaxPrintAndMaxScan(@RequestBody JSONObject param) {
        Map<String, Object> companyIdMaxScan = companyCustomAppVersionDao.findByCompanyIdMaxScan(param.getString("companyId"));
        if (companyIdMaxScan.size() > 0 && companyIdMaxScan.get("custom_app_id") != null) {
            String customAppId = companyIdMaxScan.get("custom_app_id").toString();
            if (param.get("maxPrint") != null) {
                JSONObject json = new JSONObject();
                Integer maxPrintNumber = customAppVersionDao.updateMaxPrint(param.getLong("maxPrint"), customAppId);
                json.put("maxPrintNumber", maxPrintNumber);
                return json;
            } else if (param.get("maxScan") != null) {
                JSONObject json = new JSONObject();
                Integer maxScanNumber = customAppVersionDao.updateMaxScan(param.getIntValue("maxScan"), customAppId);
                json.put("maxScanNumber", maxScanNumber);
                return json;
            }
        }
        return "传入数据有误";
    }

    /**
     * 获取银行下面的  公司信息
     */
    @GetMapping(value = "/bankAndConpany/{companyId}")
    public Object bankAndConpany(@PathVariable("companyId") String companyId) {
        return companyDao.bankAndCompany(companyId);
    }

    @GetMapping(value = "/companyIdMsg/{companyId}")
    public Object MsgCompany(@PathVariable("companyId") String companyId) {
        return companyDao.findById(companyId);
    }

}
